/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [XPath_Example.java]
 * Creation Date        [08-21-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_05_xpath;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * XPath 示例
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class XPath_Example {

	public static void xpathExample() throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		Document document = xmlReader.read(new File("src/xml/Student.xml"));

		List<?> nodes = document.selectNodes("//STUDENT");
		System.out.println("There are " + nodes.size() + " students");

		Node node = document.selectSingleNode("//NAME");
		System.out.println(node.getName() + "=" + node.getText());

		// 这里的node可以被转换为Attribute
		node = document.selectSingleNode("//@*");
		System.out.println(node.getName() + "=" + node.getText());

		String studentId = "s00001";
		node = document.selectSingleNode("//STUDENT[@STUDENT_ID='" + studentId
				+ "']");// 多个属性条件用AND / OR 连接, 注意单引号的使用
		System.out.println(node != null ? "Find" : "Not found");
	}

	public static void main(String[] args) {
		try {
			xpathExample();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}
